//
//  WBComposeTextView.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/27.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

class WBComposeTextView: UITextView {

    lazy var placeholderLabel = UILabel()
    
    override func awakeFromNib() {
       setupUI()
    }
    
    private func setupUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: Notification.Name.UITextViewTextDidChange, object: nil)
        
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.font = font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.frame.origin = CGPoint(x: 5, y: textContainerInset.top)
        placeholderLabel.sizeToFit()
        
        addSubview(placeholderLabel)
    }
    
    @objc func textChanged() {
        placeholderLabel.isHidden = hasText
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension WBComposeTextView {
    /// 图文混排
    ///
    /// - parameter em: 表情模型
    func insertEmotion(em: CZEmotionModel?) {
        guard let em = em else {
            deleteBackward()
            return
        }
        
        if let emoji = em.emoji,
            let textRange = selectedTextRange {
            replace(textRange, withText: emoji)
            return
        }
        
        let imageText = em.imageText(font: font!)
        let attr = NSMutableAttributedString(attributedString: attributedText)
        let range = selectedRange
        attr.replaceCharacters(in: range, with: imageText)
        
        attributedText = attr
        
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
        // 调用代理方法使发布按钮状态变化
        delegate?.textViewDidChange?(self)
        // 调用该方法使placeholderlabel隐藏
        textChanged()
    }
    
    /// 返回对应纯文本的字符串
    var emotionText: String {
        
        guard let attr = attributedText else {return ""}
        
        var result = String()
        
        attr.enumerateAttributes(in: NSRange(location: 0, length: attr.length), options: [], using: { (dic, range, _) in
            
            if let attachment = dic["NSAttachment"] as? CZEmotionAttachment {
                result += attachment.chs ?? ""
            }else{
                let subStr = (attr.string as NSString).substring(with: range)
                result += subStr
            }
        })
        
        return result
    }

}
